﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace Sobiens.Connector.Admin.DAL
{
    class BaseList
    {
        protected SPWeb _web;
        protected SPList _list;
        protected String _listName;

        public static readonly String FIELD_INTERNAL_NAME_CONFIGURATION = "Configuration";

        protected BaseList(String listName)
        {

            DataContractSerializer dcs = new DataContractSerializer(typeof(String));
            DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(String));
            
            _listName = listName;
            _web = SPContext.Current.Web;
            _list = _web.Lists.TryGetList(listName);
            if (_list == null)
                throw new Exception(String.Format("The list with the name '{0}' could not be found in '{1}'", _listName, _web.Url));
        }

        public virtual SPListItemCollection GetAllItems(string[] viewFieldNames)
        {
            SPQuery query = new SPQuery();

            StringBuilder sb = new StringBuilder();
            foreach (String fieldName in viewFieldNames)
            {
                if (String.IsNullOrEmpty(fieldName) == false)
                {
                    sb.AppendFormat("<FieldRef Name='{0}'/>", fieldName);
                }
            }
            query.ViewFields = sb.ToString();
            
            query.Query = "<Where></Where>";

            SPListItemCollection result = _list.GetItems(query);
            return result;
        }

        public virtual SPListItem GetItem(Guid id)
        {
            return _list.GetItemByUniqueId(id);
        }

        public virtual SPListItem GetFirstItem()
        {
            return (_list.ItemCount>0) ? _list.Items[0] : null;
        }


        public virtual void DeleteItem(string itemGuid)
        {
            SPListItem item = _list.GetItemByUniqueId(new Guid(itemGuid));
            item.Delete();
        }
    }
}

